package com.wechat.admin.controller;

import com.wechat.admin.annoation.AuthCheck;
import com.wechat.admin.common.BaseResponse;
import com.wechat.admin.common.CommonConstants;
import com.wechat.admin.common.ResultUtils;
import com.wechat.admin.exception.BusinessException;
import com.wechat.admin.exception.ErrorCode;
import com.wechat.admin.exception.ThrowUtils;
import com.wechat.admin.model.request.AccessTokenRequest;
import com.wechat.admin.model.request.UserLoginRequest;
import com.wechat.admin.model.request.UserRegisterRequest;
import com.wechat.admin.model.vo.UserInfoByGroupVo;
import com.wechat.admin.model.vo.UserLoginInfoVo;
import com.wechat.admin.service.UserService;
import com.wechat.admin.service.impl.TokenBlacklistServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author:sjb
 * @CreateTime:2024-12-14
 * @Description: 用户相关视图
 * @Version：1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private TokenBlacklistServiceImpl tokenBlacklistService;

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        long userRegister = userService.userRegister(userAccount, password, checkPassword);
        return ResultUtils.success(userRegister);
    }

    @PostMapping("/login")
    public BaseResponse<String> login(@RequestBody UserLoginRequest userLoginRequest) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String token = userService.login(userLoginRequest);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "生成Token异常");
        }
        return ResultUtils.success(token);
    }

    @GetMapping("/getCurrentUser")
    public BaseResponse<UserLoginInfoVo> getCurrentUser() {
        UserLoginInfoVo currentLoginUser = userService.getCurrentLoginUser();
        return ResultUtils.success(currentLoginUser);
    }

    /**
     * 分配token信息给用户到组
     *
     * @param accessTokenRequest
     * @return
     */
    @PostMapping("/assignmentTokenToUser")
    @AuthCheck(mustRole = CommonConstants.ADMIN)
    public BaseResponse<Boolean> accessTokenToUser(@RequestBody AccessTokenRequest accessTokenRequest) {
        ThrowUtils.throwIf(accessTokenRequest == null, ErrorCode.PARAMS_ERROR);
        Boolean tokenToUser = userService.assignmentTokenToUser(accessTokenRequest);
        return ResultUtils.success(tokenToUser);
    }


    /**
     * 登出接口
     * @param token 包含 JWT 的 Authorization Header
     * @return 登出结果
     */
    @PostMapping("/logout")
    public BaseResponse<String> logout(@RequestHeader("Authorization") String token) {
        SecurityContextHolder.clearContext();
        if (token == null || !token.startsWith(CommonConstants.TOKEN_PREFIX)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"Token无效");
        }
        String actualToken = token.substring(CommonConstants.TOKEN_PREFIX.length());
        log.info("本次加入黑名单的token为：{}",actualToken);
        try {
            // 将 Token 加入黑名单
            tokenBlacklistService.addTokenToBlacklist(actualToken);
            return ResultUtils.success("成功登出");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"登出失败");
        }
    }

    /**
     * 取所有用户名
     * @return
     */
    @GetMapping("/getAllUsers")
    public BaseResponse<List<String>> getAllUsersName(){
        List<String> allUsers = userService.getAllUsers();
        return ResultUtils.success(allUsers);
    }


    /**
     * 根据组获取所有用户信息
     * @return
     */
    @GetMapping("/getAllUsersInfoByGroup")
    @AuthCheck(mustRole = CommonConstants.ADMIN)
    public BaseResponse<UserInfoByGroupVo> getAllUsersInfoByGroup(){
        UserInfoByGroupVo allUsersByGroup = userService.getAllUsersByGroup();
        return ResultUtils.success(allUsersByGroup);
    }

}
